/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.psc.ejb;

import com.mycompany.psc.entities.Department;
import java.util.List;
import java.util.Set;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

/**
 *
 * @author A7med
 */
@Stateless
public class DepartmentsManager {

    @PersistenceContext(unitName = "com.mycompany_PSC_war_1.0-SNAPSHOTPU")
    EntityManager em;

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    public List<Department> getChildren(int parent) {
        TypedQuery<Department> query = em.createNamedQuery("Department.findAllChildren", Department.class);
        query.setParameter("parent", parent);
        return query.getResultList();
    }

    public List<Department> getAll() {
        TypedQuery<Department> query = em.createNamedQuery("Department.findAll", Department.class);

        return query.getResultList();
    }

    public Department getByName(String name) {
        TypedQuery<Department> query = em.createNamedQuery("Department.findByName", Department.class);
        query.setParameter("name", name);
        try {
            return query.getResultList().get(0);
        } catch (ArrayIndexOutOfBoundsException e) {
            return null;
        }
    }
    public Department getById(String id) {
        TypedQuery<Department> query = em.createNamedQuery("Department.findById", Department.class);
        query.setParameter("id", Integer.parseInt(id));
        try {
            return query.getResultList().get(0);
        } catch (ArrayIndexOutOfBoundsException e) {
            return null;
        }
    }

    public void saveChanges(Department d) {
        em.merge(d);
    }

    public void delete(Department d) {
        Department removable=em.getReference(Department.class, d.getId());
        
        em.remove(removable);
    }
    public void save(String name, String desc, Set<Department> read, Set<Department> write, int parent) {
        Department d = new Department();
        System.err.println("saving:" + name + desc);
        if (desc.equals("")) {
            desc = "No Description Entered";
        }
        d.setDesc(desc);
        d.setName(name);
        d.setParent(parent);
        if (read != null) {
            d.setReadAccess(read);
        }
        if (write != null) {
            d.setWriteAccess(write);
        }
        em.persist(d);
    }
}
